﻿namespace Site2AppWP8
{
    using System;
    using System.Diagnostics;
    using System.IO.IsolatedStorage;
    using System.Text.RegularExpressions;
    using System.Windows;
    using Microsoft.Phone.Scheduler;

    public class ScheduledAgent : ScheduledTaskAgent
    {
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        static ScheduledAgent()
        {
            // Subscribe to the managed exception handler
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override async void OnInvoke(ScheduledTask task)
        {
            var tilePollFeed = this.GetTilePollFeed();
            var tileType = this.GetTileType();
            var showTileImage = this.GetShowTileImage();

            if (!string.IsNullOrWhiteSpace(tilePollFeed))
            {
                await RssTileNotification.LoadRssTileNotification(tilePollFeed, tileType, showTileImage);
            }

#if DEBUG
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
            System.Diagnostics.Debug.WriteLine("Periodic task is started again: " + task.Name);
#endif

            this.NotifyComplete();
        }

        /// Code to execute on Unhandled Exceptions
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        private string GetTilePollFeed()
        {
            var userSettings = IsolatedStorageSettings.ApplicationSettings;

            if (userSettings.Contains("TilePollFeed"))
            {
                var tilePollFeed = (string)userSettings["TilePollFeed"];

                foreach (Match match in Regex.Matches(tilePollFeed, "{.+}"))
                {
                    var userSettingName = match.Value as string;
                    var trimmedUserSettingName = userSettingName.Substring(1, userSettingName.Length - 2);

                    if (userSettings.Contains(trimmedUserSettingName))
                    {
                        tilePollFeed = tilePollFeed.Replace(userSettingName, (string)userSettings[trimmedUserSettingName]);
                    }
                    else
                    {
                        return string.Empty;
                    }
                }

                return tilePollFeed;
            }

            return string.Empty;
        }

        private int GetTileType()
        {
            var userSettings = IsolatedStorageSettings.ApplicationSettings;

            if (userSettings.Contains("TileType"))
            {
                return (int)userSettings["TileType"];                
            }

            return 0;
        }

        private bool GetShowTileImage()
        {
            var userSettings = IsolatedStorageSettings.ApplicationSettings;

            if (userSettings.Contains("ShowImage"))
            {
                return (bool)userSettings["ShowImage"];
            }

            return false;
        }
    }
}